import { updateCarTrajectory } from "../../../api/index";
import { initLine } from "../../../util/carTrajectory.js";
import { getDistance } from "../Model/getDistance.js"
let getLongitude = 0;
let getLatitude = 0;
let map = null;
// let timer = null;
export const getPosition = (trajectoryList, orderId) => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition( // getCurrentPosition跟setInterval类似，请求多次
      (position) => {
        const setPositon = () => {
          getLongitude = position.coords.longitude; // 经度,
          getLatitude = position.coords.latitude; // 纬度
          console.log(getLongitude, getLatitude);
        };
        if (getLongitude && getLatitude) {
          const m = parseFloat(getDistance(
            getLongitude,
            getLatitude,
            position.coords.longitude,
            position.coords.latitude
          ).distanceStr);
          console.log('路程m', m);
          /** 位置变动1米以上才进行更新操作 */
          if (m > 0) {
            console.log('当前位置距离', m);
            console.log('当当前经纬度', trajectoryList);
            // 将经纬度加到数组里面
            trajectoryList.push([
              position.coords.longitude,
              position.coords.latitude
            ]);
            updateCarTrajectory({
              position: trajectoryList.slice(-1)[0],
              id: orderId
            }).then(({data}) => {
            })
            initLine(map, trajectoryList);
          }
          console.log('距离上一次变了'+m+'米');
        }
        setPositon();
      },
      function (error) {
        var errorType = [
          "您拒绝共享位置信息",
          "获取不到位置信息",
          "获取位置信息超时"
        ];
        alert(errorType[error.code - 1]);
      }
    );
  }

  // timer = setInterval(getPosition, 5000)
  // return timer;
}